using System;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace Survivor
{
	[Serializable]
	public class EnemyWave
	{
		public float GeneratorSeconds;
		public GameObject EnemyPrefab;
		public float Seconds = 10;
	}	
	public partial class EnemyGenerator : ViewController
	{
		[SerializeField]
		public List<EnemyWave> EnemyWaves = new List<EnemyWave>();

		public bool IsLastWave => enemyWaveQueue.Count == 0;
		
		private float currentGenerateSeconds;
		private float currentWaveSeconds;
		private Queue<EnemyWave> enemyWaveQueue = new Queue<EnemyWave>();
		public static EnemyWave CurrentEnemyWave { get; private set; } = null;
		[SerializeField]
		private int waveCount = 0;

		public static BindableProperty<int> EnemyCnt = new BindableProperty<int>(0);


		private void Start()
		{
			foreach (var enemyWave in EnemyWaves)
			{
				enemyWaveQueue.Enqueue(enemyWave);
			}
		}

		private void Update()
		{
			if (!Player.Instance)
				return;

			
			if (CurrentEnemyWave == null && enemyWaveQueue.Count > 0)
			{
				CurrentEnemyWave = enemyWaveQueue.Dequeue();
				currentGenerateSeconds = 0;
				currentWaveSeconds = 0;
				waveCount++;
			}

			if (CurrentEnemyWave != null)
			{
				currentGenerateSeconds += Time.deltaTime;
				currentWaveSeconds += Time.deltaTime;

				if (currentGenerateSeconds > CurrentEnemyWave.GeneratorSeconds)
				{
					currentGenerateSeconds = 0;

					var randomAngle = Random.Range(0, 360f);
					var randomRadians = randomAngle * Mathf.Deg2Rad;
					var dir = new Vector3(Mathf.Cos(randomRadians), Mathf.Sin(randomRadians));
					var generatorPos = Player.Instance.transform.position + (dir * 10);

					CurrentEnemyWave.EnemyPrefab.Instantiate()
						.Position(generatorPos)
						.Show();
				}

				if (currentWaveSeconds > CurrentEnemyWave.Seconds)
				{
					CurrentEnemyWave = null;
				}
			}
		}

		private void OnDestroy()
		{
			CurrentEnemyWave = null;
		}
	}
}
